﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SchedulerLite.Client
{
    public class SchedulerLiteClient
    {
        private string _connStr;
        public SchedulerLiteClient(string connStr)
        {
            _connStr = connStr;
        }

        public string NewDelayTask(DelayTask task)
        {
            if (task == null)
            {
                return "任务不能为空";
            }
            if (string.IsNullOrEmpty(task.Url))
            {
                return "url不能为空";
            }
            if (task.TriggerTime <= DateTime.Now.AddSeconds(5))
            {
                return "触发时间不能小于当前时间";
            }
            using (var conn = new SqlConnection(_connStr))
            {
                conn.Open();
                var cmd = conn.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = @"INSERT INTO DelayTask (Name ,Url ,Method ,PostData ,TriggerTime ,MaxRetryCount ,RetryCount ,RetrySeconds ,TimeoutSeconds ,SuccessFlag ,AddTime ,Enable ) VALUES 
(@Name ,@Url ,@Method ,@PostData ,@TriggerTime ,@MaxRetryCount ,@RetryCount ,@RetrySeconds ,@TimeoutSeconds ,@SuccessFlag ,@AddTime, 1)";
                cmd.Parameters.Add(new SqlParameter("@Name", task.Name ?? string.Empty));
                cmd.Parameters.Add(new SqlParameter("@Url", task.Url));
                cmd.Parameters.Add(new SqlParameter("@Method", task.Method ?? "GET"));
                cmd.Parameters.Add(new SqlParameter("@PostData", task.PostData ?? string.Empty));
                cmd.Parameters.Add(new SqlParameter("@TriggerTime", task.TriggerTime));
                cmd.Parameters.Add(new SqlParameter("@MaxRetryCount", task.MaxRetryCount));
                cmd.Parameters.Add(new SqlParameter("@RetryCount", task.RetryCount));
                cmd.Parameters.Add(new SqlParameter("@RetrySeconds", task.RetrySeconds));
                cmd.Parameters.Add(new SqlParameter("@TimeoutSeconds", task.TimeoutSeconds));
                cmd.Parameters.Add(new SqlParameter("@SuccessFlag", task.SuccessFlag ?? string.Empty));
                cmd.Parameters.Add(new SqlParameter("@AddTime", DateTime.Now));
                var flag = cmd.ExecuteNonQuery();
                if (flag > 0)
                {
                    return null;
                }
                else
                {
                    return "添加失败";
                }
            }
        }
    }
}
